package de.baumann.browser.tasks;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;

import java.io.File;
import java.io.FileNotFoundException;

public class SaveImageTaask extends AsyncTask<String, Void, File> {
    private Context mContext;

    public SaveImageTaask(Context context) {
        this.mContext = context;
    }

    @Override
    protected File doInBackground(String... strings) {
        String imgUrl = strings[0];
        try {
            return Glide.with(mContext)
                    .load(imgUrl)
                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(File file) {
        super.onPostExecute(file);
        if (file == null) {
            return;
        }
        try {
            MediaStore.Images.Media.insertImage(mContext.getContentResolver(),
                    file.getPath(), file.getName(), null);
            mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
            Toast.makeText(mContext, "已保存至相册", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
